/**
 * 商家接口
 */

const express = require('express')
const router = express.Router()
const pool = require('../../db/db')
const Response = require('../../utils/ResponseData')

/**
 * url: http://localhost:3000/bus/getAll/:page/:pageSize
 * @params page:  当前页码
 * @params pageSize： 一页显示的条数
 */
router.get('/getAll/:page/:pageSize',(req,res,next) => {
    // 接收前端参数
    let {page,pageSize} = req.params
    // 计算startIndex
    let startIndex = (page - 1) * pageSize
    // 将pageSize转换为数值
    pageSize = parseInt(pageSize)
    // 编写sql
    let sql = `select * from business order by b_score desc limit ?, ?`
    pool.querySync(sql,[startIndex,pageSize])
        .then(result => {
            console.log(result)
            if(result.length > 0) {
                res.send(Response.success(result, "商家信息查询成功！"))

            } else{
                res.send(Response.error("商家信息查询失败！"))
            }
        })
        .catch(err => {
            if(err) {
                console.log('Bus.js=>/bus/getAll:',err)
                next(err)
                return
            }

        })
})

/**
 * 2.根据id查询商家接口
 * url: http://localhost:3000/bus/getById/:id
 * @params id: 商家id
 */
router.get('/getById/:id',(req,res,next) => {
    let {id} = req.params
    // 编写sql
    const sql = `select * from business where b_id=?`
    // 执行sql
    pool.query(sql,[id],(err,result) => {
        if(err) {
            console.log('Bus.js=>/bus/getById/:id:',err)
            next(err)
            return
        }
        if(result.length > 0) {
            res.send(Response.success(result, "商家信息查询成功！"))
        } else{
            res.send(Response.error("商家信息查询失败！"))
        }
    })
})

module.exports = router